package leetcode;

public class NumberOfSegmentsInString {

	public static void main(String[] args) {
		String string = "  23 6      5";
		String[] strings = string.split(" ");
		for (int i = 0; i < strings.length; i++) {
			System.out.println("xianshi :" + strings[i] + ":nm");
		}
	}

	public int countSegments(String s) {
		if (s == null || s.equals("")) {
			return 0;
		}
		char[] chas = s.toCharArray();
		if (chas.length <= 1) {
			return chas[0] == ' ' ? 0 : 1;
		}
		int count = 0;
		boolean isWord = false;
		for (int i = 1; i < chas.length; i++) {
			if (chas[i] == ' ' && chas[i - 1] != ' ') {
				count++;
				isWord = false;
			} else if (chas[i] != ' ') {
				isWord = true;
			}
		}
		return isWord ? ++count : count;
	}
	
	//others consice code
	public int countSegments2(String s){
		int res = 0;
		for (int i = 0; i < s.length(); i++){
			if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' '))
				res++;
		}
		return res;
	}
	
	//others clean code
	public int countSegments3(String s) {
        s = s.trim();
        if(s.length() == 0) return 0;
        int count = 1;
        for(int i = 0; i + 1 < s.length(); i++){
          if(s.charAt(i) == ' ' && s.charAt(i + 1) != ' '){
        	  count++;
          }
        }
        return count;  
    }
}
